package com.lanlian.cayman.activity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.lanlian.cayman.CalculationService;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.OMSMessage;
import com.lanlian.cayman.R;
import com.lanlian.cayman.fragment.InformationFragment;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.fragment.MineFragment;
import com.lanlian.cayman.fragment.TradeFragment;
import com.lanlian.cayman.rabbitmq.MQCallbackImpl;
import com.lanlian.cayman.rabbitmq.MQConsumer;
import com.lanlian.cayman.rabbitmq.MQFactory;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.MessageDialog;
import com.lanlian.cayman.view.UpdateVersionDialog;
import com.lanlian.commonlib.Receiver.NetWorkChangReceiver;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.MessageInfo;
import com.lanlian.commonlib.bean.ReqMessage;
import com.lanlian.commonlib.bean.ReqOnlineStatus;
import com.lanlian.commonlib.bean.ReqSubmitPreRegister;
import com.lanlian.commonlib.bean.ReqUpdateVersion;
import com.lanlian.commonlib.bean.ReqUserRegister;
import com.lanlian.commonlib.bean.RespMessage;
import com.lanlian.commonlib.bean.RespUpdateVersion;
import com.lanlian.commonlib.bean.UpdateVersionInfo;
import com.lanlian.commonlib.bean.db.DBMessage;
import com.lanlian.commonlib.common.RabbitMqConfig;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.utillib.AppUtils;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.ToastUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/14 8:56
 *     desc   : 主页面
 *     version: 1.0
 * </pre>
 */
public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup mRadioGroup;
    private TextView mTvPoint;

    private FragmentManager mFragmentManager;

    private MarketFragment mMarketFragment;
    private TradeFragment mTradeFragment;
    private InformationFragment mInfoFragment;
    private MineFragment mMineFragment;

    private long exitTime = 0;
    private MQConsumer mqConsumer;
    private MQConsumer mqConsumer2;
    private Timer timer;
    private NetWorkChangReceiver netWorkChangReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            mFragmentManager = getSupportFragmentManager();//重新创建Manager，防止此对象为空
            mFragmentManager.popBackStackImmediate(null, 1);//弹出所有fragment
        }
        initView();
        setListeners();
        mRadioGroup.check(R.id.rb_market);

        subscribe();
        if (mDBManager.isLogined()) {
            subscribe2();
            timer = new Timer(true);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    VolleyRequestUtils.getInstance().sendRequest(MainActivity.this.toString(), new ReqOnlineStatus(), null);
                }
            }, 10000, 1200000);
        }

        setBackFrontListener();
        registerNetwork();

        getMessageList();
        updateVersion();
        int item = getIntent().getIntExtra("item", -1);
        switch (item) {
            case 3:
                mRadioGroup.check(R.id.rb_mine);
                break;
            default:
                break;
        }
    }

    @Override
    protected void initView() {
        super.initView();
        mRadioGroup = findViewById(R.id.radio_group);
        mFragmentManager = getSupportFragmentManager();
        mTvPoint = findViewById(R.id.tv_point);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mRadioGroup.setOnCheckedChangeListener(this);
    }

    private void registerNetwork() {
        //注册网络状态监听广播
        netWorkChangReceiver = new NetWorkChangReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkChangReceiver, filter);
    }

    private void setBackFrontListener() {
        mBackFrontListener = new BackFrontListener() {
            @Override
            public void onBackFront(boolean isBackground) {
                if (isBackground) {
                    if (mqConsumer != null) {
                        mqConsumer.close();
                        mqConsumer.setMessageListner(null);
                        MQFactory.getInstance().removeConsumer(mqConsumer);
                        mqConsumer = null;
                    }
                } else {
                    subscribe();
                }
            }
        };
    }

    private void getMessageList() {
        if (mDBManager.isLogined()) {
            VolleyRequestUtils.getInstance().getMessageList(this.toString(), new ReqMessage(), new INetWorkCallback() {
                @Override
                public void onSuccess(Object response) {
                    RespMessage respMessage = (RespMessage) response;
                    if (!CommonUtils.isListEmpty(respMessage.getInform())) {
                        List<DBMessage> messageList = new ArrayList<>();
                        for (MessageInfo messageInfo : respMessage.getInform()) {
                            messageList.add(new DBMessage(messageInfo));
                        }
                        messageList.get(0).setIsRead(1);
                        mDBManager.setMessageList(messageList);
                        setMessagePoint();
                        if (isAppOnForeground()) {
                            startActivity(new Intent(MainActivity.this, MessageDialog.class)
                                    .putExtra("messageInfo", respMessage.getInform().get(0)));
                        } else {
                            ifStartMessageDialog = true;
                        }
                    } else {
                        setMessagePoint();
                    }
                }

                @Override
                public void onFail(BaseResponse baseResponse) {
                }
            });
        }
    }

    private void updateVersion() {
        ReqUpdateVersion reqUpdateVersion = new ReqUpdateVersion();
        reqUpdateVersion.setMarketNo("android");
        reqUpdateVersion.setVersionNo(AppUtils.getVersionCode(this));
        VolleyRequestUtils.getInstance().updateVersion(this.toString(), reqUpdateVersion, new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                RespUpdateVersion respUpdateVersion = (RespUpdateVersion) response;
                UpdateVersionInfo updateVersionInfo = respUpdateVersion.getData();
                if ("1".equals(updateVersionInfo.getHasNewVersion())) {
                    if ("1".equals(updateVersionInfo.getForceUpdate())) {
                        new UpdateVersionDialog(MainActivity.this, updateVersionInfo).show();
                    } else {
                        if (updateVersionInfo.getVersionNo() > mDBManager.getTempVersionCode()) {
                            new UpdateVersionDialog(MainActivity.this, updateVersionInfo).show();
                        }
                    }
                }
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        hideFragments(fragmentTransaction);
        switch (checkedId) {
            case R.id.rb_market:
                if (mMarketFragment == null) {
                    mMarketFragment = new MarketFragment();
                    fragmentTransaction.add(R.id.fragment, mMarketFragment);
                    fragmentTransaction.show(mMarketFragment);
                } else {
                    fragmentTransaction.show(mMarketFragment);
                }
                break;
            case R.id.rb_trade:
                if (mTradeFragment == null) {
                    mTradeFragment = new TradeFragment();
                    fragmentTransaction.add(R.id.fragment, mTradeFragment);
                } else {
                    fragmentTransaction.show(mTradeFragment);
                }
                break;
            case R.id.rb_information:
                if (mInfoFragment == null) {
                    mInfoFragment = new InformationFragment();
                    fragmentTransaction.add(R.id.fragment, mInfoFragment);
                } else {
                    fragmentTransaction.show(mInfoFragment);
                }
                break;
            case R.id.rb_mine:
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                    fragmentTransaction.add(R.id.fragment, mMineFragment);
                } else {
                    fragmentTransaction.show(mMineFragment);
                }
                break;
            default:
                break;
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏所有的Fragment,避免fragment混乱
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mMarketFragment != null) {
            transaction.hide(mMarketFragment);
        }
        if (mTradeFragment != null) {
            transaction.hide(mTradeFragment);
        }
        if (mInfoFragment != null) {
            transaction.hide(mInfoFragment);
        }
        if (mMineFragment != null) {
            transaction.hide(mMineFragment);
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.show(this, "再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            clearAssets();
            Intent intent = new Intent(this, CalculationService.class);
            stopService(intent);
            if (MQFactory.getInstance().close()) {
                LLApplication.getInstance().exitAppDelayed();
            }
        }
    }

    private void setMessagePoint() {
        boolean flag = false;
        for (DBMessage dbMessage : mDBManager.getMessageList()) {
            if (dbMessage.getIsRead() == 0) {
                flag = true;
                break;
            }
        }
        mTvPoint.setVisibility(flag ? View.VISIBLE : View.GONE);
    }

    /**
     * 订阅行情MQ
     */
    private void subscribe() {
        if (mqConsumer == null) {
            mqConsumer = MQFactory.getInstance().createConsumer(new MQCallbackImpl(), "trade_yshq", "android_yshq");
            mqConsumer.setMessageListner(new MQConsumer.MQConsumerListener() {
                @Override
                public void onMessageReceived(byte[] bytes) {
                    try {
                        HqMsg.HqMsgReq hr = HqMsg.HqMsgReq.parseFrom(bytes);
                        HqMsg.YsHqInfo ysHqInfo = hr.getYshqinfo();
                        EventBusUtils.post(new EventMessage<>(EventCode.EVENT_MARKET, ysHqInfo));
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        mqConsumer.subscribe();
    }

    /**
     * 订阅订单以及资金MQ
     */
    private void subscribe2() {
        if (mqConsumer2 == null) {
            if (mDBManager.getUser() == null || mDBManager.getUser().getLUnitId() == null) {
                mDBManager.setLoginOut();
                EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_OUT_REFRESH));
                return;
            }
            mqConsumer2 = MQFactory.getInstance().createConsumer(new MQCallbackImpl(), "futures_oms_msg",
                    String.format("oms.*.%s", mDBManager.getUser().getLUnitId().toString()));
            mqConsumer2.setMessageListner(new MQConsumer.MQConsumerListener() {
                @Override
                public void onMessageReceived(byte[] bytes) {
                    try {
                        OMSMessage omsMessage = OMSMessage.parseFrom(bytes);
                        if (omsMessage.getLMsgType() == 1 || omsMessage.getLMsgType() == 2) {
                            Log.e("MainActivity", "订单状态发生改变");
                            if ("6".equals(omsMessage.getCOrderStatus()) || "7".equals(omsMessage.getCOrderStatus())) {
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                            }
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                        } else if (omsMessage.getLMsgType() == 11) {
                            Log.e("MainActivity", "消息推送");
                            getMessageList();
                        }
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        mqConsumer2.subscribe();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unregisterReceiver(netWorkChangReceiver);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int item = intent.getIntExtra("item", -1);
        switch (item) {
            case 0:
                mRadioGroup.check(R.id.rb_market);
                break;
            case 1:
                EventBusUtils.post(new EventMessage(EventCode.EVENT_FRAGMENT_POSITION));
                mRadioGroup.check(R.id.rb_trade);
                break;
            case 3:
                mRadioGroup.check(R.id.rb_mine);
                break;
            default:
                break;
        }
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_LOGIN_REFRESH:
                if (mDBManager.isLogined()) {
                    subscribe2();
                    timer = new Timer(true);
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            VolleyRequestUtils.getInstance().sendRequest(MainActivity.this.toString(), new ReqOnlineStatus(), null);
                        }
                    }, 10000, 1200000);
                }
                break;
            case EventCode.EVENT_LOGIN_OUT_REFRESH:
                MobclickAgent.onProfileSignOff();
                clearAssets();
                if (mqConsumer2 != null) {
                    mqConsumer2.close();
                    mqConsumer2 = null;
                }
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                break;
            case EventCode.EVENT_FUCK_OUT_REFRESH:
                MobclickAgent.onProfileSignOff();
                clearAssets();
                if (mqConsumer2 != null) {
                    mqConsumer2.close();
                    mqConsumer2 = null;
                }
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                startActivity(new Intent(this, MainActivity.class));
                break;
            case EventCode.EVENT_PRE_REGISTER:
                ReqUserRegister reqUserRegister = LLApplication.reqUserRegister;
                if (TextUtils.isEmpty(reqUserRegister.getMobile())) {
                    return;
                }
                ReqSubmitPreRegister reqSubmitPreRegister = new ReqSubmitPreRegister();
                reqSubmitPreRegister.setUserSurname(reqUserRegister.getUserSurname());
                reqSubmitPreRegister.setUserName(reqUserRegister.getUserName());
                reqSubmitPreRegister.setMobile(reqUserRegister.getMobile());
                reqSubmitPreRegister.setMail(reqUserRegister.getMail());
                reqSubmitPreRegister.setMale(reqUserRegister.getMale());
                reqSubmitPreRegister.setIdCard(reqUserRegister.getIdCard());
                reqSubmitPreRegister.setIdCardBack(reqUserRegister.getIdCardBack());
                reqSubmitPreRegister.setIdCardFront(reqUserRegister.getIdCardFront());
                reqSubmitPreRegister.setRiskDisclosure(reqUserRegister.getRiskDisclosure());
                reqSubmitPreRegister.setAutograph(reqUserRegister.getAutograph());
                reqSubmitPreRegister.setBankCard(reqUserRegister.getBankCard());
                reqSubmitPreRegister.setBankProvince(reqUserRegister.getBankProvince());
                reqSubmitPreRegister.setBankCity(reqUserRegister.getBankCity());
                reqSubmitPreRegister.setBankType(reqUserRegister.getBankType());
                reqSubmitPreRegister.setBankBranch(reqUserRegister.getBankBranch());
                reqSubmitPreRegister.setPostalAddress(reqUserRegister.getPostalAddress());
                reqSubmitPreRegister.setAssetsSource(reqUserRegister.getAssetsSource());
                reqSubmitPreRegister.setAssetsType(reqUserRegister.getAssetsType());
                reqSubmitPreRegister.setNetAssets(reqUserRegister.getNetAssets());
                reqSubmitPreRegister.setUserIncome(reqUserRegister.getUserIncome());
                reqSubmitPreRegister.setBankruptcyDesc(reqUserRegister.getBankruptcyDesc());
                reqSubmitPreRegister.setCareerType(reqUserRegister.getCareerType());
                reqSubmitPreRegister.setCompanyType(reqUserRegister.getCompanyType());
                reqSubmitPreRegister.setUserPosition(reqUserRegister.getUserPosition());
                reqSubmitPreRegister.setCompanyAddress(reqUserRegister.getCompanyAddress());
                reqSubmitPreRegister.setCompanyName(reqUserRegister.getCompanyName());
                reqSubmitPreRegister.setWorkingLife(reqUserRegister.getWorkingLife());
                reqSubmitPreRegister.setBiNo(reqUserRegister.getBiNo());
                reqSubmitPreRegister.setPostalProvince(reqUserRegister.getPostalProvince());
                reqSubmitPreRegister.setPostalCity(reqUserRegister.getPostalCity());
                reqSubmitPreRegister.setAccountType(reqUserRegister.getAccountType());
                VolleyRequestUtils.getInstance().submitPreRegister(this.toString(), reqSubmitPreRegister, null);
                break;
            case EventCode.EVENT_COLOR_TOPIC_CHANGE:
                finish();
                clearAssets();
                MQFactory.getInstance().close();
                RabbitMqConfig rabbitMqConfig = SystemConfig.getMQConfig();
                MQFactory.getInstance().init(rabbitMqConfig.getIp(), rabbitMqConfig.getPort(),
                        rabbitMqConfig.getUser(), rabbitMqConfig.getPassword());
                startActivity(new Intent(this, this.getClass())
                        .putExtra("item", 3));
                overridePendingTransition(0, 0);
                break;
            case EventCode.EVENT_MESSAGE_POINT:
                setMessagePoint();
                break;
            default:
                break;
        }
    }

    private void clearAssets() {
        LLApplication.positionPnl = null;
        LLApplication.deposit = null;
        LLApplication.deposit2 = null;
        LLApplication.availableFunds = null;
        LLApplication.actualPnl = null;
        LLApplication.overnightDeposit = null;
        LLApplication.dynamicPnl = null;
        LLApplication.beginCash = null;
        LLApplication.intoCash = null;
        LLApplication.withdrawCash = null;
        LLApplication.drawAble = null;
        LLApplication.reqUserRegister = null;
        LLApplication.reqUpdateUserRegister = null;
    }

    private boolean ifStartMessageDialog = false;

    @Override
    protected void onResume() {
        super.onResume();
        if (ifStartMessageDialog) {
            ifStartMessageDialog = false;
            DBMessage dbMessage;
            if (CommonUtils.isListEmpty(mDBManager.getMessageList())) {
                return;
            } else {
                dbMessage = mDBManager.getMessageList().get(0);
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setId(dbMessage.getId().intValue());
            messageInfo.setType(dbMessage.getType());
            messageInfo.setTitle(dbMessage.getTitle());
            messageInfo.setContent(dbMessage.getContent());
            messageInfo.setPushTime(dbMessage.getPushTime());
            startActivity(new Intent(MainActivity.this, MessageDialog.class)
                    .putExtra("messageInfo", messageInfo));
        }
    }

    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

}
